package cn.gcjxsc.filter;

import cn.gcjxsc.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author pumbaa
 * @since 1.0
 */
@WebFilter(urlPatterns = {"/member/*"}, filterName = "memberPreFilter")
public class MemberPreFilter implements Filter {
    private AuthService authService;

    private boolean checkAuth = false;

    @Autowired
    public MemberPreFilter(AuthService authService) {
        this.authService = authService;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (checkAuth) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String sessid = request.getParameter("PHPSESSID");
            if (StringUtils.isEmpty(sessid)) {
                sessid = AuthUtil.getPHPSessionId(request);
            }
            if (StringUtils.isEmpty(sessid)) {
                AuthUtil.ajaxResponse(response);
            }
            Integer memberId = authService.getAuthIden("member_" + sessid);
            if (null == memberId) {
                AuthUtil.ajaxResponse(response);
            }
            else {
                HttpSession session = request.getSession();
                session.setAttribute("memberId", memberId);
            }
        }
        else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
